package xyz.coolcsm.security.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import xyz.coolcsm.security.entity.SysUser;
import xyz.coolcsm.security.entity.SysUserInfo;
import xyz.coolcsm.security.mapper.SysUserMapper;
import xyz.coolcsm.security.mapper.SysUserRoleMapper;
import xyz.coolcsm.security.service.SysUserInfoService;
import xyz.coolcsm.security.service.SysUserService;

import java.util.List;
/**
 * @author 什锦
 * @since 2021-06-1
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserInfoService sysUserInfoService;

    @Autowired
    RsaKeyProperties properties;


    @Override
    public SysUser selectByName(String userName) {
        return sysUserMapper.selectByName(userName);
    }

    @Override
    public SysUser queryById(Integer id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public List<SysUser> queryAllByLimit(int offset, int limit) {
        Page<SysUser> page = new Page<>(offset, limit);
        Page<SysUser> result = sysUserMapper.selectPage(page, null);
        return result.getRecords();
    }

    @Override
    public SysUser insert(SysUser sysUser) {
       String str1 = new String(Base64.encodeBase64(properties.getPrivateKey().getEncoded()));
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = null;
        try {
            encode = bCryptPasswordEncoder.encode(RsaUtils.decrypt(sysUser.getPassword(),str1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        sysUser.setPassword(encode);
        sysUserMapper.insert(sysUser);
        SysUser sysUser1 = sysUserMapper.selectByName(sysUser.getUsername());
        sysUserRoleMapper.addRole(sysUser1.getId(),null);
        SysUserInfo sysUserInfo = new SysUserInfo();
        sysUserInfo.setUid(sysUser1.getId().toString());
        sysUserInfo.setNickname(sysUser1.getNickName());
        sysUserInfoService.save(sysUserInfo);
        return sysUser;
    }

    @Override
    public SysUser update(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
        return sysUser;
    }

    @Override
    public boolean deleteById(Integer id) {
        return sysUserMapper.deleteById(id) > 0;
    }
}
